package com.ptu.spzx.manager.service.impl;

import com.ptu.spzx.manager.mapper.SysMenuMapper;
import com.ptu.spzx.manager.mapper.SysUserMapper;
import com.ptu.spzx.model.entity.system.SysMenu;
import com.ptu.spzx.model.entity.system.SysUser;
import com.ptu.spzx.security.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名数据库的用户信息
        SysUser sysUser = sysUserMapper.selectByUserName(username);
        System.out.println(sysUser);
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户不存在");
        }
        List<SysMenu> menusByUserId = sysMenuMapper.findByUserId(sysUser.getId());
        List<String> collect = menusByUserId.stream().map(SysMenu::getAuthPermission).collect(Collectors.toList());
        return new LoginUser(sysUser,collect);
    }
}
